<?php

namespace app\admin\model;

use app\admin\library\Auth;
use think\Model;
use traits\model\SoftDelete;

class Investment extends Model
{

    use SoftDelete;


    // 表名
    protected $name = 'investment';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'content_time_text',
        'category_name'
    ];

    //获取分类名称
    public function getCategoryNameAttr($value, $data)
    {
        $value = $value ? $value : $data['investment_category_id'];
        $name  = InvestmentCategoryModel::where('id', '=', $value)->value('platename');
        return !empty($name) ? $name:'';
    }

    // 数据插入成功后的回调方法
    protected static function init()
    {
        self::afterInsert(function ($model) {
            $model->admin_id = (new Auth)->id;
            if ($model->content_time == null) {
                $model->content_time = time();
            }
            if (date('Y-m-d', $model->content_time) == '1970-01-01') {
                $model->content_time = ($model->content_time - 25569) * 86400;
            }
            $model->save();
        });
    }

    public function getContentTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['content_time']) ? $data['content_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setContentTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function admin()
    {
        return $this->belongsTo('Admin', 'admin_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


}
